package com.hula.onion.book.server.spider.platforms.iqianjin;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:爱钱进spider
 * Create Date:2018/1/17 19:33
 *
 * @author liangbing
 * @version 1.0
 */
@Component("iQianJinSpider")
public class IQianJinSpider extends SpiderCommon {

    /**
     * 登陆页URL
     */
    private static final String LOGIN_PAGE_URL = "https://www.iqianjin.com/user/login";
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.iqianjin.com/user/logon";

    /**
     * 获取验证码URL
     */
    private static final String CAPTCHA_URL = "https://www.iqianjin.com/user/getCode";

    /**
     * 校验验证码URL
     */
    private static final String CHECK_CAPTCHA_URL = "https://www.iqianjin.com/user/checkCode";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "http://www.iqianjin.com/userCenter/statistics/getMyAssets";

    @Autowired
    private IQianJinSpiderHelper iQianJinSpiderHelper;

    /**
     * 执行爬取操作
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);

        HttpClientContext httpContext = HttpClientContext.create();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);

        Map<String, Object> paraMap = iQianJinSpiderHelper.installRequestParams(loginForm);

        //1. 从缓存中获取cookie，设置到cookie store中
        CookieUtils.setCookie(loginForm.getPlatformId(), loginForm.getUserId(), cookieStore);

        //校验一次验证码
        Map<String, Object> params = new HashMap<>(2);

        params.put("code", loginForm.getTicket());
        params.put("name", loginForm.getTicket());

        BasicHeader header = new BasicHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:58.0) Gecko/20100101 Firefox/58.0");

        String checkStr = HttpUtils.post(CHECK_CAPTCHA_URL, params, httpContext, header);

        boolean checkStatus = JSONObject.parseObject(checkStr).getBoolean("success");

        //验证码校验失败
        if (!checkStatus) {

            commonResponse = new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);

            commonResponse.setMsg(JSONObject.parseObject(checkStr).getString("message"));

            return commonResponse;
        }

        //模拟登陆
        String loginStr = HttpUtils.post(LOGIN_URL, paraMap, httpContext);

        logger.info("[IQianJinSpider] Http response result:{}", loginStr);

        if (!StringUtils.isEmpty(loginStr)) {

            boolean status = JSONObject.parseObject(loginStr).getBoolean("success");

            //登陆成功
            if (status) {

                // 爬取数据
                String html = HttpUtils.get(GET_ACCOUNT_INFO_URL, httpContext);

                AccountInfo accountInfo = iQianJinSpiderHelper.parseAccountBalance(html);

                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(accountInfo);

                return commonResponse;

            } else {
                commonResponse = new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);

                commonResponse.setMsg(JSONObject.parseObject(loginStr).getString("message"));

                return commonResponse;
            }
        }

        return commonResponse;
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL;
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_PAGE_URL;
    }
}
